package com.airbnb.mvrx.sample.features.clickread

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.airbnb.epoxy.Carousel
import com.airbnb.mvrx.fragmentViewModel
import com.airbnb.mvrx.sample.core.BaseFragment
import com.airbnb.mvrx.sample.core.simpleController
import com.airbnb.mvrx.sample.features.clickread.models.ClickReadViewModel
import com.airbnb.mvrx.sample.features.clickread.views.cRContentContainerView
import com.airbnb.mvrx.sample.views.loadingRow
import com.alibaba.fastjson.JSON
import com.yt.ytdeep.client.dto.ClickReadDTO
import com.yt.ytdeep.client.dto.ClickReadPage

class ClickReadFragment : BaseFragment() {

    private val viewModel: ClickReadViewModel by fragmentViewModel()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Carousel.setDefaultItemSpacingDp(0)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val rootView: View? = super.onCreateView(inflater, container, savedInstanceState)
        toolbar.title = "我的Fragment"
        return rootView
    }

    override fun epoxyController() = simpleController(viewModel) { state ->
        val resp = state.resp()
        if (resp == null) {
            loadingRow {
                id("loading")
            }
            return@simpleController
        }
        if (state.resp.complete) {

            val dataStr = JSON.toJSONString(resp?.data)
            val clickReadDTO: ClickReadDTO = JSON.parseObject(dataStr, ClickReadDTO::class.java)
            var pageList: MutableList<ClickReadPage> = mutableListOf()
            clickReadDTO.chapters.forEach { eachC ->
                eachC?.sections?.forEach { eachS ->
                    pageList.addAll(eachS.pages)
                }
            }

            val newPageList = pageList.filterIndexed { index, clickReadPage -> index < 29 }
            cRContentContainerView {
                id("content")
                content(newPageList)
            }

        }


    }

}